package com.statapp;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

/** 
 * A Service to create status bar notifications.
 * 
 * @author Peter Goldenbogen (Munich University of Applied Science)
 * @version 1.0 
 */

public class NotificationService extends Service {
	
	private static final int NOTIFICATION_ID = 123456;
	
    public class NotificationBinder extends Binder {
    	NotificationService getService() {
            return NotificationService.this;
        }
    }
	
	@Override
	public void onCreate(){
		Log.d("statapp","Notification Service called");
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId){
		String message = intent.getStringExtra("payload");
		notifyUser("KPI Notification", message);
		return START_STICKY;
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	/**
	 * Produces the Notification which will appear in the systems status bar
	 * @param message The ticker text which will be displayed
	 * @param tText The message which will be displayed
	 */

	private void notifyUser(String tText, String message) {
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    	
    	int icon = R.drawable.ic_launcher;
    	CharSequence tickerText = tText;

    	CharSequence contentTitle = "KPI Notification";
    	CharSequence contentText = message;

        Intent intent = new Intent(this, StatAppActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        
        Notification notif = new Notification(icon, tickerText, System.currentTimeMillis());
        notif.setLatestEventInfo(this, contentTitle, contentText, contentIntent);
        
        notif.flags = notif.FLAG_AUTO_CANCEL;
    	mNotificationManager.notify(NOTIFICATION_ID, notif);
	}
}
